package fr.lille.inria.adam.lifl.EcoGardeInventory.Tasks;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.util.Log;

public class LoginTask extends HttpAsyncTask<String, Integer> {

	private static final String TAG = "LoginTask";
	protected final static String urlWelcomePage = "http://signature.enm-lille.fr/enlmsig/index.php?cont=accueil";
	protected final static String authUrl = "http://signature.enm-lille.fr/enlmsig/index.php?cont=login&event=identification";
	public final static int NO_CONNECTION = 0;
	public final static int SUCCES_CODE = 2;
	public final static int ERROR_CONNECTION = 3;
	public final static int INCORRECT_USERNAME_CODE = 4;
	public final static int INCORRECT_PASSWORD_CODE = 8;

	@Override
	protected Integer doInBackground(String... params) {
		Log.d(TAG, "start");
		
		HttpGet GetReq = new HttpGet(urlWelcomePage);
		HttpResponse response = browser.execute(GetReq);
		
		if (response == null) {
			Log.d(TAG, "error: NO_CONNECTION");
			return NO_CONNECTION;
		}
		
		
        HttpEntity entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            try {
				entity.consumeContent();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        }
        System.out.println("Initial set of cookies:");
       
        CookieStore cs = (CookieStore) browser.getContext().getAttribute(ClientContext.COOKIE_STORE);

        if (cs.getCookies().size()<=0) {
            System.out.println("None");
        } else {
        	for (int i = 0; i < cs.getCookies().size(); i++) {

    			Log.d(TAG, "Initial set of cookies: " + cs.getCookies().get(i));
    		}
        }
		
		
		HttpPost logRequest = new HttpPost(authUrl);
		logRequest.addHeader("X-Requested-With", "XMLHttpRequest");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		
		nameValuePairs.add(new BasicNameValuePair("USER", params[0]));
		nameValuePairs.add(new BasicNameValuePair("PASS", params[1]));

		HttpEntity e = null;
		try {
			e = new UrlEncodedFormEntity(nameValuePairs);
		} catch (UnsupportedEncodingException e1) {
			Log.d(TAG, "error UnsupporteEncodingException");
		}

		logRequest.setEntity(e);
		//HttpResponse response = browser.execute(logRequest);
		response = browser.execute(logRequest);

		if (response == null) {
			Log.d(TAG, "error: NO_CONNECTION");
			return NO_CONNECTION;
		}

		String s = super.getStringContent(response);
		Integer result = (s.contains("Utilisateur incorrect")) ? INCORRECT_USERNAME_CODE
				: (s.contains("Mot de passe incorrect")) ? INCORRECT_USERNAME_CODE
						: SUCCES_CODE;
		result = testError(s);
		Log.d(TAG, "finished: " + result);
		return result;
	}

	private int testError(String s) {
		Document optNavigo = Jsoup.parse(s);
		Elements optGroupTags = optNavigo.select("title");

		if (optGroupTags.size() > 0) {
			String res = optGroupTags.get(0).text();
			if (res.equals("403 Forbidden"))
				return ERROR_CONNECTION;
		}
		return 2;
	}
}
